/**
 * Copyright (C) Skywares Information Technology, LTD. 
 * All Rights Reserved.
 *
 * UserArgumentResolver.java created on 2020年2月3日 上午10:08:29 by Lyon Lu 
 */
package com.mvc.server.miaosha.config;

import java.util.Objects;
import java.util.stream.Stream;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.mvc.server.miaosha.common.CommonContant;
import com.mvc.server.miaosha.pojo.MiaoshaUser;
import com.mvc.server.miaosha.service.MiaoshaUserService;

/**
 * <pre>
 * Description:
 * 	类似HttpServletRequest可直接在controller方法上使用
 * @author Lyon Lu
 * @date 2020年2月3日 上午10:08:29
 *
 * </pre>
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver{
	
	@Resource
	private MiaoshaUserService miaoshaUserService;

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return MiaoshaUser.class == parameter.getParameterType();
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
		
		String paramToken = request.getParameter(CommonContant.COOKIE_NAME_TOKEN);
		
		String cookieToken = getCookieValue(request, CommonContant.COOKIE_NAME_TOKEN);
		
		if (StringUtils.isBlank(paramToken) && StringUtils.isBlank(cookieToken)) {
			return null;
		}
		
		String token = StringUtils.isNotBlank(cookieToken) ? cookieToken : paramToken;
		
		return miaoshaUserService.getUserByToken(response, token);
	}

	/**
	 * Description:
	 * 		method description here
	 * @param request
	 * @param cookieName
	 * @return String      
	 * @throws                                 
	 */
	private String getCookieValue(HttpServletRequest request, String cookieName) {
		
		Cookie[] cookies = request.getCookies();
		if (Objects.isNull(cookies) || cookies.length == 0) {
			return null;
		}
		
		return Stream.of(cookies)
				.filter(re -> Objects.equals(cookieName, re.getName()))
				.findFirst().map(Cookie::getValue).orElse(null);
	}

}
